package com.example.myapplication.tack_30;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.graphics.RenderNode;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.myapplication.R;
import com.example.myapplication.tack_30.adapter.AddressAdapter;
import com.example.myapplication.tack_30.adapter.CaiDanAdapter;
import com.example.myapplication.tack_30.data.AddressData;
import com.example.myapplication.tack_30.data.CreateData;
import com.example.myapplication.tack_30.data.CreateJson;
import com.example.myapplication.tack_30.data.OrderItemList;
import com.example.myapplication.tack_30.data.ProductData;
import com.example.myapplication.utils.Common;
import com.example.myapplication.utils.OkHttpTool;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import okhttp3.OkHttpClient;

public class ConfirmActivity extends AppCompatActivity {
    private ImageView exit;
    private List<AddressData.DataDTO> listAddress;
    private LinearLayout select;
    private  String takeout;
    private TextView address1;
    private TextView name;
    private TextView phone;
    private Gson gson;
    private AlertDialog alertDialog;
    private Intent intent;
    private ProductData dataDTO;
    private RecyclerView caiDan;
    private List<ProductData.DataDTO> listProduct;
    private int number;
    private float price;
    private TextView num;
    private float total = 0;
    private TextView submit;
    private JSONObject jsonObject;
    private OrderItemList orderItem;
    private List<OrderItemList> list;
    private AddressData.DataDTO add;
    private CreateJson createJson;
    private TextView dian_jia_name;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tack_32_activity_confirm);
        init();
        initExit();
        selectAddress();
        getCaiDan();
        initSubmit();
    }
    private void initSubmit() {
        //"addressDetail": "大连理工大学 教学楼 A3-118",
        //"label": "学校",
        //"name": "王先生",
        //"phone": "13800000000",
        //"amount": 64,
        //"orderItemList": [
        //{
        //"productId": 1,
        //"quantity": 2
        //},
        //{
        //"productId": 30,
        //"quantity": 1
        //}
        //],
        //"sellerId": 1
        //}
        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(!TextUtils.isEmpty(add.getAddressDetail()) && !"".equals(add.getAddressDetail())){
                    try {
                        jsonObject.put("addressDetail",add.getAddressDetail());
                        jsonObject.put("label",add.getLabel());
                        jsonObject.put("name",add.getName());
                        jsonObject.put("phone",add.getPhone());
                        jsonObject.put("amount",String.valueOf(total));
                        jsonObject.put("sellerId",dataDTO.getData().get(0).getSellerId());
//                        jsonObject.put("orderItemList",list);
                        JSONArray jsonArray = new JSONArray();
                        for (OrderItemList orderItemList : list) {
                            JSONObject jsonObject1 = new JSONObject();
                            jsonObject1.put("productId",orderItemList.getProductId());
                            jsonObject1.put("quantity",orderItemList.getQuantity());
                            jsonArray.put(jsonObject1);
                        }
                        jsonObject.put("orderItemList",jsonArray);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    String json = jsonObject.toString();
                    initCreate(json);
                }else{
                    Toast.makeText(ConfirmActivity.this,"未填地址",Toast.LENGTH_SHORT).show();
                }

            }
        });
    }
    private void initCreate(String json) {
        String url = "prod-api/api/takeout/order/create";
        OkHttpTool.doNetRequest(url, OkHttpTool.POST, CreateData.class, new OkHttpTool.NetCallback() {
            @Override
            public void onSuccess(Object obj) {
                CreateData createData = (CreateData)obj;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
//                        Toast.makeText(ConfirmActivity.this,createData.getMsg(),Toast.LENGTH_SHORT).show();
                        if(createData.getCode() == 200){
                            Intent intent = new Intent(ConfirmActivity.this,PaymentPageActivity.class);
                            intent.putExtra(Common.COMMON,createData.getOrderNo());
                            ConfirmActivity.this.startActivity(intent);
                            ConfirmActivity.this.finish();
                        }
                    }
                });
            }

            @Override
            public void onFailure(String msg) {

            }
        },json);
    }

    private void getCaiDan() {
        for (ProductData.DataDTO datum : dataDTO.getData()) {
            if(datum.getNumber()>0){
                listProduct.add(datum);
                number = datum.getNumber();
                price = (float)datum.getPrice();
                total += (price*number);
                orderItem.setProductId(dataDTO.getData().get(0).getId());
                orderItem.setQuantity(number);
                list.add(orderItem);
            }

        }
        num.setText(String.valueOf(total));
        caiDan.setAdapter(new CaiDanAdapter(listProduct,ConfirmActivity.this));
        caiDan.setLayoutManager(new LinearLayoutManager(ConfirmActivity.this));
    }

    private void selectAddress() {
        select.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder ab = new AlertDialog.Builder(ConfirmActivity.this);
                View view = LayoutInflater.from(ConfirmActivity.this).inflate(R.layout.tack_32_address,null);
                RecyclerView address = view.findViewById(R.id.address);
                TextView add_address = view.findViewById(R.id.add_address);
                String url  = "prod-api/api/takeout/address/list";
                OkHttpTool.doNetRequest(url, OkHttpTool.GET, AddressData.class, new OkHttpTool.NetCallback() {
                    @Override
                    public void onSuccess(Object obj) {
                        AddressData addressData = (AddressData)obj;
                        if(addressData.getCode() == 200){
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    address.setLayoutManager(new LinearLayoutManager(ConfirmActivity.this));
                                    address.setAdapter(new AddressAdapter(addressData.getData(), ConfirmActivity.this, new AddressAdapter.Click() {
                                        @Override
                                        public void close(String msg) {
                                            takeout = msg;
                                            add = gson.fromJson(takeout, AddressData.DataDTO.class);
                                            name.setText(add.getName());
                                            address1.setText(add.getAddressDetail());
                                            phone.setText(add.getPhone());
                                            alertDialog.dismiss();
                                        }
                                    }));
                                }
                            });
                        }
                    }

                    @Override
                    public void onFailure(String msg) {

                    }
                });
                ab.setView(view);
                alertDialog = ab.create();
                alertDialog.show();
                add_address.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(ConfirmActivity.this,AddAddressActivity.class);
                        ConfirmActivity.this.startActivity(intent);
                    }
                });
            }
        });
    }

    private void initExit() {
        exit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ConfirmActivity.this.finish();
            }
        });
    }

    private void init() {

        add = new AddressData.DataDTO();
        orderItem = new OrderItemList();
        list = new ArrayList();
        dian_jia_name = findViewById(R.id.dian_jia_name);
        submit = findViewById(R.id.submit);
        exit = findViewById(R.id.exit);
        num = findViewById(R.id.num);
        select = findViewById(R.id.select);
        address1 = findViewById(R.id.address);
        name = findViewById(R.id.name);
        phone = findViewById(R.id.phone);
        caiDan = findViewById(R.id.caiDan);
        gson = new Gson();
        intent = getIntent();
        String str = intent.getStringExtra(Common.COMMON);
        dataDTO = gson.fromJson(str, ProductData.class);
        listProduct = new ArrayList<>();
        jsonObject = new JSONObject();
        createJson = new CreateJson();
        dian_jia_name.setText(dataDTO.getData().get(0).getStoreName());
    }
}